package com.kanasco.engg.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class PaginationController extends SimpleFormController
{
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response)throws IOException,ServletException{
	
        HttpSession session=request.getSession();
        System.out.println("this is pagincontrl");
        
        String option=request.getParameter("option");
		System.out.println("Selected  is :"+option);
		
		Integer startIndex=(Integer)session.getAttribute("startIndex");
		System.out.println("startIndex"+startIndex);
		
		Integer maxIndex=(Integer)session.getAttribute("maxIndex");
		System.out.println("maxIndex"+maxIndex);
		
		session.setAttribute("previousCount", startIndex);
	  
		Integer previousCount=(Integer)session.getAttribute("previousCount");
		System.out.println("pcount  is :"+previousCount);
	  
		List pageList=(List)session.getAttribute("itemList");
		
		
		session.setAttribute("previousCount", startIndex);
		
			if(option.equalsIgnoreCase("first"))
			{
				startIndex=1;
				session.setAttribute("startIndex", startIndex);
				
			}
			
			if(option.equalsIgnoreCase("next"))
			{
				
				
				System.out.println("in next part sta inex is:"+previousCount);
				
				System.out.println("list in next is :"+pageList);
				if(previousCount+maxIndex>pageList.size())
					{
					System.out.println("Iam in if nex jdhjkfh"+previousCount+maxIndex);

					
					startIndex=previousCount;
						
					}
				else
					{
				    System.out.println("THIS IS ELSE PART of next");  
				    startIndex=previousCount+maxIndex;
				    System.out.println("in next part sta inex is:"+startIndex);
					
					}
				session.setAttribute("startIndex", startIndex);
				}
				
			
			if(option.equalsIgnoreCase("previous"))
			{
				if(previousCount-maxIndex<0)
				
			{
					
					startIndex=previousCount;
					session.setAttribute("startIndex",startIndex);
				}else{
					startIndex=previousCount-maxIndex;
					session.setAttribute("startIndex", startIndex);
			}
				}
			if(option.equalsIgnoreCase("last"))
			{ 
				
				
				System.out.println(pageList);
				startIndex=pageList.size()-maxIndex+1;
				System.out.println("strtnx nin last:"+startIndex);
					session.setAttribute("startIndex", startIndex);
			}

			

		
		
		return new ModelAndView("PickItemList","startIndex",startIndex);
	
		
	}

}
